import { useDispatch } from "react-redux";
import store from "@/store";
import { useMemo } from "react";
import { renderMenuItem } from "@/routes";
import { useLocation,matchPath} from "react-router-dom";
type TDispatch = typeof store.dispatch;
export const useAppDispatch = () => useDispatch<TDispatch>();
export const useAppTilte = () => {
    const location = useLocation();
    return useMemo(() => {
        // const path ="/" + location.pathname.split("/")[1];
        // 思路：useMemo
        // const titleObj = useMemo(()=>{
        const path = "/" + location.pathname.split("/")[1];
        // 根据路由path找到路由信息
        const info = renderMenuItem().find((v: any) => v.path === path);
        // 找到一级标题
        const title = info.label;
        // 找二级标题
        let subTitle;
        if (info.children) {
             // 1- 问题：不能确定浏览器请求的地址与路由地址匹配
            // const subInfo = info.children.find((v:any)=>v.path === location.pathname);

            // 2- 路由->path   /hospital/show/:id
            //    浏览器->path  /hospital/show/622574cc36a9ba1be763dad8

            //    matchPath:是一个方法，可以查看请求地址与路由地址是否匹配。第一个参数是路由设置的path,第二个参数是浏览器地址
            //              如果不匹配返回的是null,如果匹配返回的是匹配相关信息（对象）
            // console.log(matchPath("/a/b/:id","/a/b/c"))
            // console.log(matchPath("/hospital/show/:id","/hospital/show/622574cc36a9ba1be763dad8"))

            const subInfo = info.children.find((v:any)=>matchPath(v.path,location.pathname));
            if(subInfo) subTitle = subInfo.label;
        }
        return {
            title,
            subTitle
        }
    }, [location.pathname])
}
